package com.videoaggre.zcl.ui.widget

import android.app.Activity
import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.RelativeLayout
import com.videoaggre.zcl.R
import com.videoaggre.zcl.databinding.ViewAgefansSearchBinding
import com.videoaggre.zcl.helper.OnSearchEditorActionListener
import com.videoaggre.zcl.utils.Logger

class SearchView : RelativeLayout {
    companion object {
        const val SV_TITLE_MAIN = 1 // 在标题栏，主题渐变色
        const val SV_WHITE = 2 // 其他位置，白色
        const val SV_GREY = 3 // 搜索框灰色，其他主题背景灰色
        const val SV_TITLE_WHITE = 4 // 搜索框灰色，其他主题背景白色
    }

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(attrs)
    }

    private var mTblStyle: Int = SV_WHITE
    private var showSearchText = true
    private var mViewAgefansSearchBinding: ViewAgefansSearchBinding? = null
    var hint: String = ""
        set(value) {
            mViewAgefansSearchBinding?.searchBar?.hint = value
            field = value
        }
    var onLeftClickListener: ((view: View) -> Unit)? = null
    var clearListener: (() -> Unit)? = null
        set(value) {
            mViewAgefansSearchBinding?.run {
                searchBar.setOnEditorActionListener(OnSearchEditorActionListener { value?.invoke() })
                searchBar.clearListener = value
                tvSearch.setOnClickListener { value?.invoke() }
            }
            field = value
        }
    val text: String
        get() {
            if (mViewAgefansSearchBinding != null) {
                return mViewAgefansSearchBinding!!.searchBar.text.toString()
            }
            return ""
        }

    private fun init(attrs: AttributeSet?) {
        kotlin.runCatching {
            attrs?.let {
                val typedArray: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.SearchView)
                mTblStyle = typedArray.getInt(R.styleable.SearchView_sv_style, mTblStyle)
                showSearchText = typedArray.getBoolean(R.styleable.SearchView_sv_show_search_text, true)
                typedArray.recycle()
            }
            mViewAgefansSearchBinding = ViewAgefansSearchBinding.inflate(LayoutInflater.from(context), this, true)
            mViewAgefansSearchBinding?.run {
                flBack.setOnClickListener { if (context is Activity) (context as Activity).onBackPressed() }
            }
        }
    }
}